package com.example.demo.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.controller.Utils.ResponseMessage;
import com.example.demo.entity.User;
import com.example.demo.service.IUserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;

/**
 * 负责处理 HTTP 请求（如 /user/path）。 调用 service 层完成业务逻辑。 返回 JSON 格式的响应。
 */
@RestController // 转化为json文本
@RequestMapping("/user") // 映射一层接口 localhost:8080/user
public class UserController {
    @Autowired
    IUserService userService;

    @PostMapping()
    public ResponseMessage<User> add(@Validated @RequestBody User user) {
        Integer newUserId = userService.add(user);
        return ResponseMessage.success(newUserId);
    }

    @GetMapping("/{userId}")
    public ResponseMessage get(@PathVariable Integer userId) {
        User user = userService.get(userId);
        return ResponseMessage.success(user);
    }

    @PutMapping()
    public ResponseMessage edit(@Validated @RequestBody User user) {
        Integer newUserId = userService.update(user);
        return ResponseMessage.success(newUserId);
    }

    @DeleteMapping("/{userId}")
    public ResponseMessage delete(@PathVariable Integer userId) {
        userService.delete(userId);
        return ResponseMessage.success();
    }
}
